package com.lexiang.oauth.service;

import com.alibaba.fastjson.JSON;
import com.lexiang.oauth.entity.wx.*;
import com.lexiang.oauth.entity.wx.resp.AccessTokenResp;
import com.lexiang.oauth.entity.wx.resp.Code2SessionResp;
import com.lexiang.oauth.entity.wx.resp.PhoneNumberResp;
import com.lexiang.oauth.entity.wx.resp.UserInfoResp;
import com.lexiang.oauth.properties.WXProperties;
import com.lexiang.oauth.utils.BusinessException;
import lombok.extern.slf4j.Slf4j;
import org.bouncycastle.jce.provider.BouncyCastleProvider;
import org.bouncycastle.util.encoders.Base64;
import org.springframework.http.*;
import org.springframework.stereotype.Component;
import org.springframework.web.client.RestTemplate;

import javax.annotation.Resource;
import javax.crypto.BadPaddingException;
import javax.crypto.Cipher;
import javax.crypto.IllegalBlockSizeException;
import javax.crypto.NoSuchPaddingException;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;
import java.io.UnsupportedEncodingException;
import java.security.*;
import java.security.spec.InvalidParameterSpecException;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;

@Slf4j
@Component
public class WxAppService {


    @Resource
    private WXProperties wxProperties;

    @Resource
    private RestTemplate restTemplate;



    //登录凭证校验。通过 wx.login 接口获得临时登录凭证 code 后
    // 传到开发者服务器调用此接口完成登录流程。更多使用方法详见 小程序登录。
    public Code2SessionResp code2Session(String code){
        String url = "https://api.weixin.qq.com/sns/jscode2session?appid={appID}&secret={appSecret}&js_code={code}&grant_type=authorization_code";
        HashMap<String, Object> param = new HashMap<>();
        param.put("appID" ,wxProperties.getAppId());
        param.put("appSecret" ,wxProperties.getAppSecret());
        param.put("code", code);
        Code2SessionResp body;
        ResponseEntity<Code2SessionResp> result = restTemplate.getForEntity(url, Code2SessionResp.class,param);
        body = change(result);
        if(body.getErrcode() != 0){
            throw new BusinessException(body.getErrcode(),body.getErrmsg());
        }
        return body;
    }

    public UserInfoResp getUserInfo(UserInfoReq userInfoReq){
        // 被加密的数据
        byte[] dataByte = Base64.decode(userInfoReq.getEncryptedData());
        // 加密秘钥
        byte[] keyByte = Base64.decode(userInfoReq.getSessionKey());
        // 偏移量
        byte[] ivByte = Base64.decode(userInfoReq.getIv());

        try {

            // 如果密钥不足16位，那么就补足.  这个if 中的内容很重要
            int base = 16;
            if (keyByte.length % base != 0) {
                int groups = keyByte.length / base + (keyByte.length % base != 0 ? 1 : 0);
                byte[] temp = new byte[groups * base];
                Arrays.fill(temp, (byte) 0);
                System.arraycopy(keyByte, 0, temp, 0, keyByte.length);
                keyByte = temp;
            }
            // 初始化
            Security.addProvider(new BouncyCastleProvider());
            Cipher cipher = Cipher.getInstance("AES/CBC/PKCS7Padding", "BC");
            SecretKeySpec spec = new SecretKeySpec(keyByte, "AES");
            AlgorithmParameters parameters = AlgorithmParameters.getInstance("AES");
            parameters.init(new IvParameterSpec(ivByte));
            cipher.init(Cipher.DECRYPT_MODE, spec, parameters);// 初始化
            byte[] resultByte = cipher.doFinal(dataByte);
            if (null != resultByte && resultByte.length > 0) {
                String result = new String(resultByte, "UTF-8");
                UserInfoResp userInfoResp = JSON.parseObject(result, UserInfoResp.class);
                return userInfoResp;
            }
        } catch (NoSuchAlgorithmException e) {
            log.error(e.getMessage(), e);
        } catch (NoSuchPaddingException e) {
            log.error(e.getMessage(), e);
        } catch (InvalidParameterSpecException e) {
            log.error(e.getMessage(), e);
        } catch (IllegalBlockSizeException e) {
            log.error(e.getMessage(), e);
        } catch (BadPaddingException e) {
            log.error(e.getMessage(), e);
        } catch (UnsupportedEncodingException e) {
            log.error(e.getMessage(), e);
        } catch (InvalidKeyException e) {
            log.error(e.getMessage(), e);
        } catch (InvalidAlgorithmParameterException e) {
            log.error(e.getMessage(), e);
        } catch (NoSuchProviderException e) {
            log.error(e.getMessage(), e);
        }
        return null;
    }


    public PhoneNumberResp getPhoneNumber(String code){
        AccessTokenResp accessToken1 = getAccessToken();
        String url = "https://api.weixin.qq.com/wxa/business/getuserphonenumber?access_token="+accessToken1.getAccess_token();
        HashMap<String, String> param = new HashMap<>();
        param.put("code" ,code);
        HttpHeaders headers = new HttpHeaders();
        HttpEntity<Map<String, String>> httpEntity = new HttpEntity<>(param,headers);
        System.out.println(httpEntity);
        ResponseEntity<PhoneNumberResp> response = restTemplate.postForEntity(url, httpEntity, PhoneNumberResp.class);
        PhoneNumberResp body = change(response);
        if(body.getErrcode() != 0){
            throw new BusinessException(body.getErrcode(), body.getErrmsg());
        }
        return body;

    }

    private AccessTokenResp getAccessToken(){
        String url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid={appID}&secret={appSecret}";
        HashMap<String, Object> param = new HashMap<>();
        param.put("appID" ,wxProperties.getAppId());
        param.put("appSecret" ,wxProperties.getAppSecret());
        ResponseEntity<AccessTokenResp> result = restTemplate.getForEntity(url, AccessTokenResp.class,param);
        AccessTokenResp body = change(result);
        if(body.getErrcode() != 0){
            throw new BusinessException(body.getErrcode(), body.getErrmsg());
        }

        return body;
    }


    public <T> T change(ResponseEntity<T> responseEntity){
        T body = responseEntity.getBody();
        log.info("wx:code2Session接口返回数据"+ JSON.toJSONString(body));
        return body;
    }


}
